import 'dart:convert';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:yysk_app/model/common_model/customer_service_qa_list_model.dart';
import 'package:yysk_app/net/api/common_api.dart';
import 'package:yysk_app/net/api/user_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/my_webview/my_webview_page.dart';
import 'package:yysk_app/pages/nft_pages/home_pages/news_detail/news_detail_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/widget/refresh_and_scroll_widget.dart';

class CustomerServicePage extends StatefulWidget {
  static const path = '/customerService';
  const CustomerServicePage({super.key});

  @override
  State<CustomerServicePage> createState() => _CustomerServicePageState();
}

class _CustomerServicePageState extends State<CustomerServicePage> {
  // 将 list 提升为类的成员变量
  List<dynamic> lists = [];
  late String url = '';
  late dynamic timeObj = '';
  final ScrollController scrollController = ScrollController();
  int pageNum = 1;
  int pageSize = 20;
  final qaList = RxList<CustomerServiceListItemModel>();
  GlobalController globalController = Get.find();

  @override
  void initState() {
    super.initState();
    setState(() {
      url = globalController.staticInfo.value!.customerWechat ?? '';
      timeObj = json.decode(
        globalController.staticInfo.value!.serviceTime ?? '',
      );
    });
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        _getQueryState(loadMore: true);
      }
    });
    _getQueryState();
  }

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    return Scaffold(
      backgroundColor: AppColors.backgroundColorBlack,
      bottomNavigationBar: BottomAppBar(
        color: AppColors.backgroundColorBlack,
        padding: EdgeInsets.symmetric(horizontal: 14.px, vertical: 0.px),
        child: ButtonWidget(
          height: 40.px,
          width: 347.px,
          label: '联系客服',
          fontSize: 15.px,
          fontWeight: FontWeight.w500,
          onPressed: () {
            launchUrl(
              Uri.parse("https://work.weixin.qq.com/kfid/kfc54002238bab52544"),
            );
          },
        ),
      ),
      body: MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: Obx(() {
          return Stack(
            children: [
              SizedBox(
                width: context.width,
                child: ImageAssetWidget(
                  width: 375.px,
                  height: 582.px,
                  imageUrl: 'static/images/bg.png',
                ),
              ),
              Column(
                children: [
                  Padding(
                    padding: EdgeInsets.only(top: top, bottom: 0.px),
                    child: CustomAppBar2(
                      title: '我的客服',
                      context: context,
                      backgroundColor: AppColors.backgroundColor,
                    ),
                  ),
                  Stack(
                    children: [
                      Container(
                        width: 375.px,
                        height: 117.px,
                        padding: EdgeInsets.only(left: 32.px, right: 0.px),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            hiSpace(height: 30.px),
                            Text(
                              'hi，有什么可以帮您？',
                              style: TextStyle(
                                color: AppColors.fontColor,
                                fontSize: 20.px,
                              ),
                            ),
                            SizedBox(height: 10.px),
                            Text(
                              '服务时间：${timeObj['type'] == 0 ? '每天' : '工作日'} ${timeObj['startTime']}-${timeObj['endTime']}',
                              style: TextStyle(
                                color: AppColors.fontColorGray99,
                                fontSize: 14.px,
                              ),
                            ),
                          ],
                        ),
                      ),
                      Positioned(
                        top: 0,
                        right: 20.px,
                        child: ImageAssetWidget(
                          imageUrl: 'static/images/kefu_logo.png',
                          width: 117.px,
                          height: 117.px,
                        ),
                      ),
                    ],
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 14.px, right: 14.px),
                    child: Container(
                      width: 375.px,
                      padding: EdgeInsets.only(
                        right: 18.px,
                        left: 18.px,
                        top: 14.px,
                      ),
                      decoration: BoxDecoration(
                        color: AppColors.backgroundColorBlackLight,
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(12.px),
                          topRight: Radius.circular(12.px),
                        ),
                      ),
                      child: Text(
                        '猜您想问',
                        style: TextStyle(
                          fontSize: 16.px,
                          color: AppColors.fontColor,
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(left: 14.px, right: 14.px),
                      child: Container(
                        padding: EdgeInsets.all(14.px),
                        decoration: BoxDecoration(
                          color: AppColors.backgroundColorBlackLight,
                          borderRadius: BorderRadius.only(
                            bottomLeft: Radius.circular(12.px),
                            bottomRight: Radius.circular(12.px),
                          ),
                        ),
                        child: RefreshAndScrollWidget(
                          onRefresh: _handleRefresh,
                          scrollController: scrollController,
                          itemBuilder: (item, index) => _itemWidget(item),
                          itemCount: qaList.length,
                          items: qaList,
                          emptyText: '暂无数据~',
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          );
        }),
      ),
    );
  }

  _itemWidget(item) {
    return GestureDetector(
      onTap: () {
        Get.toNamed(
          NewsDetailPage.path,
          arguments: {
            'id': 0,
            'content': item.answer,
            'title': '',
            'labelName': '',
            'createTime': '',
          },
        );
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 0.px, vertical: 16.px),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              width: 1.px,
              color: AppColors.backgroundColorGreyF8,
            ),
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            SizedBox(
              width: 280.px,
              child: Text(
                '${item.question}',
                style: TextStyle(
                  fontSize: 12.px,
                  color: AppColors.fontColorGrayE8,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ),
            ImageAssetWidget(
              imageUrl: 'static/images/right_ico.png',
              height: 14.px,
              width: 14.px,
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _handleRefresh() async {
    _getQueryState();
    return;
  }

  Future<void> _getQueryState({loadMore = false}) async {
    if (loadMore) {
      pageNum++;
    } else {
      pageNum = 1;
    }
    try {
      http.netFetch<CustomerServiceListModel>(
        CommonApi.getQaList,
        method: Method.post,
        params: {'pageNum': pageNum, 'pageSize': pageSize},
        success: (result) {
          List<CustomerServiceListItemModel> items = result.data?.list ?? [];
          if (loadMore && items.isEmpty) {
            pageNum--;
          }
          if (!loadMore) {
            qaList.clear();
          }
          qaList.addAll(items);
        },
      );
    } catch (e) {
      if (loadMore) {
        pageNum--;
      }
    }
  }
}
